package com.aeye.mbr.upms.server.controller;

import com.aeye.mbr.common.base.BaseController;
import com.aeye.mbr.common.util.MD5Util;
import com.aeye.mbr.common.util.WebUtils;
import com.aeye.mbr.sms.SmsTemplateType;
import com.aeye.mbr.upms.client.shiro.session.UpmsSessionDao;
import com.aeye.mbr.upms.common.constant.UpmsConstant;
import com.aeye.mbr.upms.common.constant.UpmsResult;
import com.aeye.mbr.upms.common.constant.UpmsResultConstant;
import com.aeye.mbr.upms.dao.model.UpmsParam;
import com.aeye.mbr.upms.dao.model.UpmsUser;
import com.aeye.mbr.upms.rpc.api.*;
import com.zheng.sms.rpc.service.SmsApiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 单点登录管理
 * Created by shengpeng on 2018/4/10.
 */
@Controller
@RequestMapping("/sso")
@Api(value = "单点登录管理", description = "单点登录管理")
public class SSOController extends BaseController {

    private final static Logger _log = LoggerFactory.getLogger(SSOController.class);

    @Autowired
    UpmsSystemService upmsSystemService;

    @Autowired
    UpmsUserRoleService upmsUserRoleService;

    @Autowired
    UpmsUserService upmsUserService;

    @Autowired
    UpmsApiService upmsApiService;

    @Autowired
    UpmsSessionDao upmsSessionDao;

    @Autowired
    SmsApiService smsApiService;

    @Autowired
    UpmsParamService upmsParamService;

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String serverSessionId = session.getId().toString();
        // 判断是否已登录，如果已登录，则回跳

        // code校验值
        if (subject.isAuthenticated() || subject.isRemembered()) {
            return "redirect:"+request.getContextPath()+"/manage/index";
        }
        return "/sso/login.jsp";
    }

    @ApiOperation(value = "登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object login(HttpServletRequest request, HttpServletResponse response, @RequestParam String username,@RequestParam String password) {
        String rememberMe = request.getParameter("rememberMe");
        if (StringUtils.isBlank(username)) {
            return new UpmsResult(UpmsResultConstant.EMPTY_USERNAME, "帐号不能为空！");
        }
        if (StringUtils.isBlank(password)) {
            return new UpmsResult(UpmsResultConstant.EMPTY_PASSWORD, "密码不能为空！");
        }
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String sessionId = session.getId().toString();
        // 判断是否已登录，如果已登录，则回跳，防止重复登录
        // code校验值
        if (!(subject.isAuthenticated() || subject.isRemembered())) {
            // 使用shiro认证
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
            try {
                if (BooleanUtils.toBoolean(rememberMe)) {
                    usernamePasswordToken.setRememberMe(true);
                } else {
                    usernamePasswordToken.setRememberMe(false);
                }
                subject.login(usernamePasswordToken);
            } catch (UnknownAccountException e) {
                return new UpmsResult(UpmsResultConstant.INVALID_USERNAME, "帐号不存在！");
            } catch (IncorrectCredentialsException e) {
                return new UpmsResult(UpmsResultConstant.INVALID_PASSWORD, "密码错误！");
            } catch (LockedAccountException e) {
                return new UpmsResult(UpmsResultConstant.INVALID_ACCOUNT, "帐号已锁定！");
            }
        }
        return new UpmsResult(UpmsResultConstant.SUCCESS, request.getContextPath()+"/manage/index");
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request) {
        // shiro退出登录
        SecurityUtils.getSubject().logout();
        return "redirect:/";
    }

    @ApiOperation(value = "忘记密码")
    @RequestMapping(value = "/forget", method = RequestMethod.GET)
    public String forget(HttpServletRequest request) {
        return "/sso/forget.jsp";
    }

    @ApiOperation(value = "注册用户")
    @RequestMapping(value = "/regist", method = RequestMethod.GET)
    public String toRegist(HttpServletRequest request) {
        return "/sso/regist.jsp";
    }

    @ApiOperation(value = "注册用户")
    @RequestMapping(value = "/regist", method = RequestMethod.POST)
    @ResponseBody
    public Object regist(HttpServletRequest request, UpmsUser upmsUser,@RequestParam String code) {
        if (smsApiService.checkSmsCode(upmsUser.getPhone(), UpmsConstant.DEFAULT_TOP_ORG_ID, SmsTemplateType.TYPE_REGIST, code)) {
            smsApiService.clearSmsCode(upmsUser.getPhone(), UpmsConstant.DEFAULT_TOP_ORG_ID, SmsTemplateType.TYPE_REGIST);

            String salt = UUID.randomUUID().toString().replaceAll("-", "");
            upmsUser.setSalt(salt);
            upmsUser.setPassword(MD5Util.MD5(upmsUser.getPassword() + upmsUser.getSalt()));
            upmsUser = upmsUserService.createUser(upmsUser);
            if (null == upmsUser) {
                return UpmsResult.fail("帐号名已存在！");
            }
            UpmsParam upmsParam = upmsParamService.getUpmsParamByName(UpmsConstant.UPMS_PARAM_DEFALUT_ROLES_FOR_USER+"_"+upmsUser.getType());
            if(null != upmsParam){
                upmsUserRoleService.role(new String[]{upmsParam.getParamValue()},upmsUser.getUserId());
            }
            return UpmsResult.success("success");
        }else{
            return UpmsResult.fail("验证码错误");
        }
    }

    @ApiOperation(value = "获取短信验证码")
    @RequestMapping(value = "/registCode", method = RequestMethod.POST)
    @ResponseBody
    public Object code(HttpServletRequest request,@RequestParam String phone) {
        smsApiService.sendVerifyCode(phone, UpmsConstant.DEFAULT_TOP_ORG_ID, SmsTemplateType.TYPE_REGIST, 6, WebUtils.getRemoteAddr(request));
        return UpmsResult.success("success");
    }
}
